package com.hitalkie.teacher.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.Toast;

import com.google.gson.Gson;
import com.hitalkie.teacher.R;
import com.hitalkie.teacher.app.TalkieApi;
import com.hitalkie.teacher.fragment.LoadingDialogFragment;
import com.hitalkie.teacher.model.BaseResponse;
import com.hitalkie.teacher.util.OkHttpManager;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Date 06/11/2016
 *
 * @author charliema
 */

public class PasswordEditActivity extends BaseActivity {


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        initView();

    }

    private void initView() {
        setContentView(R.layout.view_password_edit);
        initTitleBar();
        findViewById(R.id.tvConfirm).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                passwordEdit();
            }
        });

        findViewById(R.id.tvPasswordForget).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent().setClass(getActivity(), PasswordForgetActivity.class));
            }
        });

        final EditText etPasswordNew = (EditText) findViewById(R.id.etPasswordNew);
        ((CheckBox) findViewById(R.id.cbEye)).setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    etPasswordNew.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                } else {
                    etPasswordNew.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                }
            }
        });

    }

    private void initTitleBar() {
        findViewById(R.id.viewTitleBarLeft).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getActivity().finish();
            }
        });
    }

    private void passwordEdit() {
        EditText etPasswordOld = (EditText) findViewById(R.id.etPasswordOld);
        EditText etPasswordNew = (EditText) findViewById(R.id.etPasswordNew);

        String passwordOld = etPasswordOld.getText().toString();
        String passwordNew = etPasswordNew.getText().toString();

        if (TextUtils.isEmpty(passwordOld)) {
            etPasswordOld.setError("不能为空");
            return;
        }
        if (TextUtils.isEmpty(passwordNew)) {
            etPasswordNew.setError("不能为空");
            return;
        }
        passwordEdit(passwordOld, passwordNew);
    }

    private void passwordEdit(String passwordOld, String passwordNew) {
        // loading dialog
        final LoadingDialogFragment loadingDialogFragment = new LoadingDialogFragment();
        loadingDialogFragment.show(getSupportFragmentManager(), "loading");

        Map<String, String> req = new HashMap<>();
        req.put("password", passwordNew);
        req.put("old_password", passwordOld);

        String url = TalkieApi.getHost() + TalkieApi.PATH_PASSWORD;
        Log.e(TAG, "req:" + url);
        Request.Builder reqBuilder = new Request.Builder().url(url);
        reqBuilder.post(RequestBody.create(OkHttpManager.JSON, new Gson().toJson(req)));
        OkHttpManager.client.newCall(reqBuilder.build())
                //
                .enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        e.printStackTrace();
                        new Handler(Looper.getMainLooper()).post(new Runnable() {
                            @Override
                            public void run() {
                                // loading dialog
                                loadingDialogFragment.dismiss();
                                Toast.makeText(getActivity(), getText(R.string.network_exception), Toast.LENGTH_LONG).show();
                            }
                        });
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        if (!response.isSuccessful()) {
                            return;
                        }
                        String jsonStr = response.body().string();
                        Log.e(TAG, "resp:" + jsonStr);

                        try {
                            final PasswordResp resp = new Gson().fromJson(jsonStr, PasswordResp.class);
                            new Handler(Looper.getMainLooper()).post(new Runnable() {
                                @Override
                                public void run() {
                                    if (resp.status.error_code == 0) {
//                                        Toast.makeText(getActivity(), getText(R.string.), Toast.LENGTH_LONG).show();
                                        Intent i = new Intent(getActivity(), MainActivity.class);
                                        i.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
                                        i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                                        startActivity(i);
                                    } else {
                                        Toast.makeText(getActivity(), resp.status.error_message, Toast.LENGTH_LONG).show();
                                        if (resp.status.error_code == 403) {
                                            // 登录授权失败
                                            startActivity(new Intent(getActivity(), SignInActivity.class));
                                        }
                                    }

                                }
                            });
                        } catch (Exception e) {
                            e.printStackTrace();
                        } finally {
                            new Handler(Looper.getMainLooper()).post(new Runnable() {
                                @Override
                                public void run() {
                                    // loading dialog
                                    loadingDialogFragment.dismiss();
                                }
                            });
                        }
                    }
                });
    }

    private static class PasswordResp extends BaseResponse {
        String token; // "",
    }

}
